package top.ffhome.blog.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.core.collection.CollUtil;
import top.ffhome.blog.entity.Article;
import top.ffhome.blog.service.ArticleService;
import top.ffhome.common.exception.BusinessException;
import top.ffhome.common.page.PageRequest;
import top.ffhome.common.result.Result;
import top.ffhome.util.bean.BeanUtil;

@CrossOrigin
@RestController
@RequestMapping("api/blog/article")
public class ArticleController {
	@Autowired
	private ArticleService articleService;

	@RequiresPermissions(value = { "blog:article:add", "blog:article:edit" }, logical = Logical.OR)
	@PostMapping(value = "/save")
	public Result save(@RequestBody Article article) {
		List<String> fields = CollUtil.newArrayList("title", "content", "status", "labelIds");
		if (!(article.getId() == null || article.getId() == 0)) {
			fields.add("id");
			fields.add("updateTime");
		}
		BeanUtil.constraintProperties(article, fields);
		if (article.getId() == null) {
			articleService.insert(article);
		} else {
			articleService.update(article);
		}
		return Result.success();
	}

	@RequiresPermissions("blog:article:remove")
	@PostMapping(value = "/delete")
	public Result delete(@RequestBody List<Long> ids) {
		try {
			articleService.delete(ids);
		} catch (BusinessException e) {
			return Result.fail(e.getMessage());
		}
		return Result.success();
	}

	@RequiresPermissions("blog:article:view")
	@PostMapping(value = "/get")
	public Result get(@RequestBody Article article) {
		if (article.getId() == null) {
			return Result.fail("参数不正确");
		}
		Article a = articleService.get(article.getId());
		a.setLabelIds(articleService.selectLabelsByArticleId(a.getId()));
		return Result.success(a);
	}

	@RequiresPermissions("blog:article:view")
	@PostMapping(value = "/findPage")
	public Result findPage(@RequestBody PageRequest request) {
		return Result.success(articleService.select(request));
	}
}
